<template>
  <div>
    <div class="create-commere-order">
      <CommerceOrderInfo
        ref="commerceOrder"
        v-model="paramsObj"
        :is-edit="isEdit"
        :tax-amount-disabled="taxAmountDisabled"
        :order-status="orderStatus"/>
      <GoodsInfo ref="goodsInfo" v-model="goodsInfo" :can-edit="!(isEdit && paramsObj.orderStatus >= 2)"/>
      <logisticsInfo v-model="logisticsInfo"/>
      <fixed-pagination>
        <div class="center">
          <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
          <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import CommerceOrderInfo from './module/commerceOrderInfo';
import GoodsInfo from './module/goodsInfo';
import logisticsInfo from './module/logisticsInfo';
import { mapState } from 'vuex';
import { addCommerce, editCommerce, getCommerceInfo } from '@/api/mengli';

export default {
  components: { CommerceOrderInfo, GoodsInfo, logisticsInfo },
  data() {
    return {
      isEdit: false,
      btnLoading: false,
      taxAmountDisabled: false,
      orderId: '',
      orderType: '',
      warehouseDefaultParams: [],
      paramsObj: {
        orderChannel: 1,
        market: '', // 销售
        marketId: '', // 销售id
        marketObj: {},
        title: '',
        ipAry: [],
        price: null,
        platformId: null,
        clientName: '',
        clientId: '',
        clientObj: {},
        orderStatus: 0,
        orderCreateTime: new Date(new Date().toLocaleDateString()).getTime(),
        payTime: new Date(new Date().toLocaleDateString()).getTime(),
        remark: '', // 备注
        attachment: [],
        actualTime: null
      },
      goodsInfo: [{
        attribute: '',
        crmCode: '',
        crmId: null,
        id: null,
        key: '',
        title: '',
        warehouseId: '',
        warehouse: '',
        goodsCoding: '',
        quantity: 1
      }],
      logisticsInfo: {
        address: '',
        cost: null,
        invoiceNum: '',
        invoiceTime: null,
        phone: ''
      },
      orderStatus: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    ipSeriesName() {
      const ipAry = this.paramsObj.ipAry;
      const name = [];
      if (ipAry && ipAry.length) {
        ipAry.forEach(i => {
          name.push(i.ipSeriesName);
        });
      }
      return name.join(',');
    }
  },
  created() {
    this.orderId = Number(this.$route.params.id) || '';
    this.orderType = this.$route.query.type || '2';
    if (this.orderId) {
      this.isEdit = true;
      this.getDetail();
    } else {
      this.isEdit = false;
      this.paramsObj.market = this.userInfo.userName;
      this.paramsObj.marketId = this.userInfo.id;
      this.paramsObj.marketObj = {
        userName: this.paramsObj.market, id: this.paramsObj.marketId
      };
    }
  },
  methods: {
    getDetail() {
      getCommerceInfo(this.orderId).then(res => {
        if (res.data) {
          res.data.ipAry = res.data.ipAry.map(item => {
            item = {
              ipName: item.ipFigure,
              ipId: item.ipFigureId,
              ipSeriesName: item.ipSeries,
              ipSeriesId: item.ipSeriesId
            };
            return item;
          });
          res.data.marketObj = {
            userName: res.data.market || '', id: res.data.marketId || ''
          };
          res.data.clientObj = {
            clientName: res.data.clientName || '', id: res.data.clientId || ''
          };
          // writeOffStatus 核销状态（0: '待核销', 1: '已完成', 2: '部分核销'）
          // 已完成和部分核销后不能编辑价格
          this.taxAmountDisabled = res.data.writeOffStatus === 1 || res.data.writeOffStatus === 2;
          res.data.payTime = res.data.payTime ? res.data.payTime * 1000 : null;
          if (res.data.orderCreateTime && res.data.orderCreateTime.toString().length === 10) {
            res.data.orderCreateTime = res.data.orderCreateTime * 1000;
          }
          res.data.actualTime = res.data.actualTime ? res.data.actualTime * 1000 : null;
          res.data.price = Number(res.data.price) / 100;
          res.data.warehouseId = res.data.warehouseId ? res.data.warehouseId : 1;
          if (res.data.warehouseId && res.data.warehouse) {
            this.warehouseDefaultParams = [{ repositoryId: res.data.warehouseId, repositoryName: res.data.warehouse }];
          }
          this.orderStatus = this.paramsObj.orderStatus;
          this.paramsObj = res.data;
          this.logisticsInfo = res.data.logisticsInfo || {};
          if (this.logisticsInfo.cost) this.logisticsInfo.cost /= 100;
          if (this.logisticsInfo.invoiceTime && this.logisticsInfo.invoiceTime.toString().length === 10) {
            this.logisticsInfo.invoiceTime = this.logisticsInfo.invoiceTime * 1000;
          }
          res.data.goodsInfo.forEach(item => {
            item.goodsCoding = {
              attribute: item.attribute,
              crmCode: item.goodsCoding,
              crmId: null,
              id: item.goodsId,
              key: item.warehouseId + '+' + item.goodsId,
              title: item.title,
              warehouse: item.warehouse,
              warehouseId: item.warehouseId
            };
            item.goodsCoding_dynamic_options = [item.goodsCoding];
          });
          this.goodsInfo = res.data.goodsInfo || [];
        }
      });
    },
    /**
     * 操作
     */
    handelParams() {
      const paramsObj = JSON.parse(JSON.stringify(this.paramsObj));
      paramsObj.ipAry = paramsObj.ipAry.map(item => {
        item = {
          ipFigure: item.ipName.split('/')[0],
          ipFigureId: item.ipId,
          ipSeries: item.ipSeriesName,
          ipSeriesId: item.ipSeriesId
        };
        return item;
      });
      if (paramsObj.price) paramsObj.price = Math.round(Number(paramsObj.price) * 100);
      if (paramsObj.payTime && paramsObj.payTime.toString().length === 13) paramsObj.payTime = Math.floor(paramsObj.payTime / 1000);
      if (paramsObj.orderCreateTime && paramsObj.orderCreateTime.toString().length === 13) paramsObj.orderCreateTime = Math.floor(paramsObj.orderCreateTime / 1000);
      if (paramsObj.actualTime && paramsObj.actualTime.toString().length === 13) paramsObj.actualTime = Math.floor(paramsObj.actualTime / 1000);
      delete paramsObj.clientObj;
      let goodsInfo = JSON.parse(JSON.stringify(this.goodsInfo));
      goodsInfo = goodsInfo.map(item => {
        const quantity = Math.floor(Number(item.quantity));
        return {
          goodsCoding: typeof item.goodsCoding === 'string' ? item.goodsCoding : item.goodsCoding.crmCode,
          goodsId: typeof item.goodsCoding === 'string' ? item.goodsId : item.goodsCoding.id,
          quantity: quantity,
          title: item.title,
          attribute: item.attribute,
          warehouseId: item.warehouseId,
          warehouse: item.warehouse
        };
      });
      const logisticsInfo = JSON.parse(JSON.stringify(this.logisticsInfo));
      if (logisticsInfo.cost) logisticsInfo.cost = Math.round(Number(logisticsInfo.cost) * 100);
      return {
        ...paramsObj,
        goodsInfo,
        logisticsInfo
      };
    },
    toSubmit() {
      const promise = [];
      promise.push(this.$refs['commerceOrder'].validate());
      promise.push(this.$refs['goodsInfo'].validate());
      Promise.all(promise).then(() => {
        const params = this.handelParams();
        if (this.isEdit) {
          this.edit(params);
        } else {
          this.add(params);
        }
      }).catch((e) => {
        this.$message.error('请检查信息是否填写完整');
        console.log(e);
      });
    },
    edit(params) {
      editCommerce(this.orderId, params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      addCommerce(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 2;
      }
      if (this.$route.params.id) {
        this.$router.push({
          name: 'mengliOrderDetail',
          params: { id: this.$route.params.id },
          query
        });
        return;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-commere-order {
  min-height: calc(100vh - 120px);
  background:rgba(255,255,255,1);
  padding: 24px;
}
.one-cell {
  width: 100%;
}
.tip {
  position: absolute;
  left: 0;
}

</style>
<style lang="scss">
  .global-select-down.ip-image .el-select-dropdown__item span {
    display: inline-block;
    width: calc(100% - 14px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
